import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import {Modal, Button, Table, message, Form, Radio, Space, Tooltip, Typography, Input, Select, Card, Row, Col} from 'antd';
import styles from '../../../components/common/PateoTable/TableList.less';
import { FormInstance } from 'antd/lib/form';


const TextArea = Input.TextArea;
const mapStateToProps = (state: any) => ({
  user: state?.menu?.userProfile
});
class RuleModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      currentCase: 0,
      currentRuleStatus: -1,
      defaultValues: {
        warnRuleName: '',
        useCase: 0,
        warnTitle: '温馨提示',
        warnShowType: 1,
        ttsEnable: 1,
        warnContent: '您的车辆已触发风控，请规范用车，谢谢。',
        ttsContent: '您的车辆已触发风控，请规范用车，谢谢。',
      }
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, user, data, dispatch, type = 'add' } = this.props
    const { defaultValues } = this.state
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      const formData = type === 'add' ? Object.assign({}, defaultValues) : Object.assign({}, data);
      this.setState({
        currentCase: formData.useCase
      })
      if (type === 'edit') {
        this.setState({
          currentRuleStatus: formData.ruleStatus
        })
      }
      this.formRef.current?.setFieldsValue({
        ...formData,
        operator: user?.accountName
      })
    }
  }

  close = () => {
    const { closeModal } = this.props;
    closeModal();
    this.setState({
      currentCase: 0,
      currentRuleStatus: -1
    })
  };

  ok = (values: any) => {
    const { dispatch,  type = 'add', refreshPage } = this.props;
    const {warnRuleName, warnTitle, warnContent, ttsEnable, ttsContent } = values
    if (!(warnRuleName && warnRuleName.trim())) {
      message.error('告警规则名称不能为空')
      return
    }
    if (!(warnTitle && warnTitle.trim())) {
      message.error('标题不能为空')
      return
    }
    if (!(warnContent && warnContent.trim())) {
      message.error('车机告警内容不能为空')
      return
    }
    if (ttsEnable == 0 && !(ttsContent && ttsContent.trim())) {
      message.error('TTS语音播报内容不能为空')
      return
    }
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/commodity/vehicle/warnRule/save',
        ...values,
        tenantCode: 'MATC', //  后面由 op端传
      },
      callback: (res: any) => {
        // this.setLoading(false);
        if (res.statusCode === '0') {
          message.success('保存成功');
          this.close();
          refreshPage && refreshPage();
        } else {
          // message.error(res.statusMessage);
        }
      },
    })
  }

  handleEnsure = () => {
    //  确定按钮
    this.formRef.current?.submit();
  }

  render() {
    const { modalVisible, type = 'add' } = this.props;
    const prefix = type && type === 'edit' ? '修改' : '新建'
    const { currentCase, currentRuleStatus } = this.state

    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" onClick={this.handleEnsure} type="primary">
          确认
        </Button>
        {/* <Button size="small" loading={loading} onClick={this.handleLock} type="primary">
          保存
        </Button> */}
      </div>
    );

    return (
      <Modal
        title={`${prefix}车机告警规则`}
        // style={{ width: '800px' }}
        width={800}
        bodyStyle={{ maxHeight: '700px' }}
        footer={footer}
        visible={modalVisible}
        onCancel={this.close}
        // onOk={this.onOk}
      >
        <Form
          style={{ marginTop: 12 }}
          ref={this.formRef}
          onFinish={this.ok}
          // size="small"
          layout="vertical"
        >
          { type === 'edit' ? (
            <Form.Item name="sid" noStyle>
              <Input type="hidden" />
            </Form.Item>
          ) : null }
          <Form.Item
            label="请输入告警规则名称"
            name="warnRuleName"
          >
            <Input placeholder="请输入告警规则名称" />
          </Form.Item>
          <Form.Item
            label="请选择使用场景"
            name="useCase"
          >
            <Radio.Group
              disabled={type==='edit' && currentRuleStatus != 0}
              onChange={(e) => {
                // console.log(e, e.target.value)
                const tempV = e.target.value
                this.setState({
                  currentCase: tempV
                })
                if (tempV === 1) {
                  this.formRef.current?.setFieldsValue({
                    warnTitle: '温馨提示',
                    warnShowType: 2,
                    ttsEnable: 0,
                  })
                }
              }}
            >
              <Radio value={1}>锁车</Radio>
              <Radio value={0}>其他</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.warnShowType !== currentValues.warnShowType
            }
          >
            {({ getFieldValue }) => {
              const tempWarnShowType = getFieldValue('warnShowType')
              // console.log('tempWarnShowType---', tempWarnShowType)
              const maxLen = tempWarnShowType === 2 ? 37 : 9
              const tempPlaceholder = tempWarnShowType === 2 ? '请输入最多37个字的标题' : '请输入最多9个字的标题'
              return (
                <Form.Item
                  label="请填写标题"
                  name="warnTitle"
                >
                  <TextArea showCount maxLength={maxLen} placeholder={tempPlaceholder} disabled={currentCase===1} />
                </Form.Item>
              )
            }}
          </Form.Item>

          <Form.Item
            label="请选择告警显示方式"
            name="warnShowType"
          >
            <Radio.Group disabled={currentCase===1} onChange={(e) => {
              const tempV = e.target.value
              const warnTitle = this.formRef.current?.getFieldValue('warnTitle')
              const warnContent = this.formRef.current?.getFieldValue('warnContent')
              // console.log(e.target.value, warnTitle)
              if (tempV === 2) {
                return
              }
              if (warnTitle && warnTitle.length > 9) {
                const tempWarnTitle = warnTitle.slice(0, 9)
                this.formRef.current?.setFieldsValue({
                  warnTitle: tempWarnTitle
                })
              }
              if (warnContent && warnContent.length > 40) {
                const tempWarnContent = warnContent.slice(0, 40)
                this.formRef.current?.setFieldsValue({
                  warnContent: tempWarnContent
                })
              }
            }}>
              <Radio value={0}>弱提醒</Radio>
              <Radio value={1}>弹框提醒</Radio>
              <Radio value={2}>霸屏提醒</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="是否开启TTS语音播报"
            name="ttsEnable"
          >
            <Radio.Group disabled={currentCase===1} onChange={(e) => {
              const tempV = e.target.value
              if (tempV === 1) {
                this.formRef.current?.setFieldsValue({
                  ttsContent: '您的车辆已触发风控，请规范用车，谢谢。'
                })
              }
            }}>
              <Radio value={0}>开启</Radio>
              <Radio value={1}>不开启</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.warnShowType !== currentValues.warnShowType
            }
          >
            {({ getFieldValue }) => {
              const tempWarnShowType = getFieldValue('warnShowType')
              const maxLen = tempWarnShowType === 2 ? 70 : 40
              const tempPlaceholder = tempWarnShowType === 2 ? '请输入最多70个字的告警内容' : '请输入最多40个字的告警内容'
              return (
                <Form.Item
                  label="请填写告警内容"
                  name="warnContent"
                >
                  <TextArea showCount maxLength={maxLen} placeholder={tempPlaceholder} />
                </Form.Item>
              )
            }}
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.ttsEnable !== currentValues.ttsEnable || currentValues.ttsEnable === 0 && prevValues.warnShowType !== currentValues.warnShowType
            }
          >
            {({ getFieldValue }) => {
              const tempTtsEnable = getFieldValue('ttsEnable')
              const tempWarnShowType = getFieldValue('warnShowType')
              const maxLen = tempWarnShowType === 2 ? 70 : 40
              const tempPlaceholder = tempWarnShowType === 2 ? '请输入最多70个字的语音播报内容' : '请输入最多40个字的语音播报内容'
              return tempTtsEnable === 0 ? (
                <Form.Item
                  label="请填写TTS语音播报内容"
                  name="ttsContent"
                >
                  <TextArea showCount maxLength={maxLen} placeholder={tempPlaceholder} />
                </Form.Item>
              ) : null
            }}
          </Form.Item>
          <Form.Item name="operator" noStyle>
            <Input type="hidden" />
          </Form.Item>
          <p style={{color: '#c3c3c3'}}>说明：锁车时，仅告警内容、TTS语音播报内容会生效</p>
        </Form>
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(RuleModal);
